package com.google.code.opengw.http;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;


public class IOSocket {
	
	private Socket socket;
	private SocketAddress socketAddress;
	private int connectionTimeout;
	
	public IOSocket(String host, int port, int connectionTimeout, boolean secure) throws UnknownHostException, IOException{
		SocketFactory socketFactory = SocketFactory.getInstance();
		socket = socketFactory.createSocket(secure);
		socketAddress = new InetSocketAddress(host, port);
		this.connectionTimeout = connectionTimeout;
	}
	
	public void connect() throws IOException{
		socket.connect(socketAddress, connectionTimeout);
	}
	
	public void setSoTimeout(int timeout) throws HTTPException{
		try{
			socket.setSoTimeout(timeout);
		} catch (Exception e) {
			throw new HTTPException(e, 500);
		}
	}
	
	public int read() throws HTTPException{
		try{
			return socket.getInputStream().read();
		} catch (Exception e) {
			throw new HTTPException(e, 500);
		}
	}
	
	public int read(byte[] buffer) throws HTTPException{
		try{
			return socket.getInputStream().read(buffer);
		} catch (Exception e) {
			throw new HTTPException(e, 500);
		}
	}
	
	public int read(byte[] buffer, int off, int len) throws HTTPException{
		try{
			return socket.getInputStream().read(buffer, off, len);
		} catch (Exception e) {
			throw new HTTPException(e, 500);
		}
	}
	
	public void write(byte[] buffer) throws HTTPException{
		try{
			socket.getOutputStream().write(buffer);
		} catch (Exception e) {
			throw new HTTPException(e, 500);
		}
	}
	
	public void write(byte[] buffer, int off, int len) throws HTTPException{
		try{
			socket.getOutputStream().write(buffer, off, len);
		} catch (Exception e) {
			throw new HTTPException(e, 500);
		}
	}
	
	public void flush() throws HTTPException{
		try{
			socket.getOutputStream().flush();
		} catch (Exception e) {
			throw new HTTPException(e, 500);
		}
	}
	
	public void close() throws HTTPException{
		try{
			socket.close();
		} catch (Exception e) {
			throw new HTTPException(e, 500);
		}
	}
}
